/*
 * @author java_deng
 * @date 2024/12/4 17:21
 * @description
 */
package org.kaka.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import org.kaka.dto.UserDto;
import org.kaka.po.UserPo;
import org.kaka.service.impl.UserServiceImpl;
import org.kaka.utils.JwtUtil;
import org.kaka.utils.PageResponseData;
import org.kaka.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.management.ServiceNotFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private JavaMailSender mailSender;


    @PostMapping("/login")
    public Object login(@RequestBody UserDto userDto, HttpSession session){
        String exception=checkParams(userDto);
        if(exception!=null){
            return fail(exception);
        }
        UserVo user=userService.login(userDto);
        if(user!=null){
            session.setAttribute("user",user);
            Map<String,Object> info = new HashMap<>();
            info.put("username",user.getUsername());
            info.put("account",user.getAccount());
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), JSONUtil.toJsonStr(info), null);
            user.setToken(token);
            return success(user);
        }
        else {
            return fail("登录失败，请检查账号或密码");
        }
    }

    @PostMapping("/adminLogin")
    public Object adminLogin(@RequestBody UserDto userDto, HttpSession session){
        String exception=checkParams(userDto);
        if(exception!=null){
            return fail(exception);
        }
        userDto.setAuth(2);
        UserVo user=userService.login(userDto);
        if(user!=null){
            session.setAttribute("user",user);
            Map<String,Object> info = new HashMap<>();
            info.put("username",user.getUsername());
            info.put("account",user.getAccount());
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), JSONUtil.toJsonStr(info), null);
            user.setToken(token);
            return success(user);
        }
        else {
            return fail("登录失败，请检查账号或密码");
        }
    }

    @PostMapping("/register")
    public Object register(@RequestBody UserDto userDto){
        try {
            checkRegisterParams(userDto);
            if(userDto.getId()!=null){
                userService.updateUserInfo(userDto);
            }else {
                userService.save(userDto);
            }

        }catch (ServiceNotFoundException exception){
            return fail(exception.getMessage());
        }
        return success("注册成功");
    }

    @GetMapping("/updateProfile")
    public Object updateProfile(UserDto userDto){
        String profile = userDto.getProfile();
        Integer id = userDto.getId();
        try {
            if(profile==null||profile.isEmpty()){
                throw new ServiceNotFoundException("未检测到头像");
            }
            if(id==null||id==0){
                throw new ServiceNotFoundException("未检测到id");
            }
            UserVo update = userService.update(userDto);

            return success("修改成功",update);
        }catch (ServiceNotFoundException e){
            return fail(e.getMessage());
        }

    }

    @PostMapping("/updateUserInfo")
    public Object updateUser(@RequestBody UserDto userDto){
        try {
            Integer id = userDto.getId();
            if(id==null||id==0){
                throw new ServiceNotFoundException("未检测到id");
            }
            UserVo update = userService.updateUserInfo(userDto);

            return success("修改成功",update);
        }catch (ServiceNotFoundException e){
            return fail(e.getMessage());
        }
    }


    /**
     * 邮件发送
     * @param
     *
     */
    @GetMapping("/sendCode")
    public Object sendMail(String emailAddr,HttpSession session){
        if(emailAddr==null||emailAddr.isEmpty()){
            return fail("邮箱不能为空");
        }
        String code=Double.toString(Math.random()).substring(2,8);
        session.setAttribute("loginCode",code);

        MimeMessagePreparator preparator=new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(emailAddr));
                mimeMessage.setFrom(new InternetAddress("dxp153247896@163.com"));
                mimeMessage.setText(code);
            }
        };
        try {
            mailSender.send(preparator);
        }
        catch (MailException ex){
            System.out.println(ex.getMessage());
        }
        return success(Long.parseLong(code)+8);
    }

    @PostMapping("/manager/list")
    public Object list(@RequestBody UserPo userPo){
        Page<UserVo> list=userService.list(userPo);
        PageResponseData<UserVo> pageResponseData=new PageResponseData<>();
        pageResponseData.setPageCount(list.getPages());
        pageResponseData.setItemCount(list.getTotal());
        pageResponseData.setResult(list.getResult());
        return success(pageResponseData);
    }

    @GetMapping("/detail")
    public Object detail(Long id){
        UserVo userVo=userService.detail(id);
        return success(userVo);
    }

    @GetMapping("/delete")
    public Object delete(Long id){
        userService.delete(id);
        return success("刪除成功");
    }

    /**
     * 以下为参数校验方法
     * @param userDto
     */

    private void checkRegisterParams(UserDto userDto) throws ServiceNotFoundException {
        String name = userDto.getUsername();
        String email = userDto.getEmail();
        String account = userDto.getAccount();
        String password = userDto.getPassword();
        String gender = userDto.getGender();
        String code = userDto.getCode();
        System.out.println(userDto);
        if(account==null||account.isEmpty()){
            throw new ServiceNotFoundException("account不能为空");
        }
        if(name==null||name.isEmpty()){
            throw new ServiceNotFoundException("name不能为空");
        }
        if(password.length()<8){
            throw new ServiceNotFoundException("密码不能少于8位数");
        }
        if(email==null||email.isEmpty()){
            throw new ServiceNotFoundException("email不能为空");
        }
        if(password==null||password.isEmpty()){
            throw new ServiceNotFoundException("password不能为空");
        }
    }
    private String checkParams(UserDto userDto) {
        String password = userDto.getPassword();
        String account = userDto.getAccount();
        if(password==null){
            return "密码不能为空";
        }
        if(account==null){
            return "账号不能为空";
        }
        return null;
    }
}
